<template>
  <el-drawer
    v-loading="drawerLoading"
    :visible.sync="dialogVisible"
    size="70%"
    :title="info.title"
    :open="open"
    :before-close="handleClose">
    <el-card style="margin: 0 20px 0 20px">
      <el-row v-if="info.from == 1">
        <el-col :span="2">
          <svg-icon name="international" style="font-size: 3rem;" />
        </el-col>
        <el-col :span="18">
          <div class="head-item">网址: {{info.domain}}</div>
          <div class="head-item">来源: 全球搜索</div>
        </el-col>
      </el-row>
      <el-row v-if="info.from == 2">
        <el-col :span="2">
          <svg-icon name="marketing" style="font-size: 3rem;" />
        </el-col>
        <el-col :span="18" style="line-height: 35px">
          <div class="head-item">来源: 数据营销</div>
        </el-col>
      </el-row>
      <el-row v-if="info.from == 0">
        <el-col :span="2">
          <svg-icon name="import" style="font-size: 3rem;" />
        </el-col>
        <el-col :span="18" style="line-height: 35px">
          <div class="head-item">来源: 外部导入</div>
        </el-col>
      </el-row>
    </el-card>

    <el-tabs v-model="activeName" style="padding: 20px">
      <el-row>
        <el-col>
          <div ref="filter" class="filter-container" style="margin-bottom: unset;">
            <template>
              <el-input
                v-model="listQuery.mobile"
                size="small"
                placeholder="请填写客户手机号码"
                style="width: 200px;margin-left:5px"
                class="filter-item filter-left"
                clearable
              />
              <el-select
                v-model="listQuery.status"
                class="filter-left"
                placeholder="请选择客户状态"
                clearable
                filterable
                size="small"
              >
                <el-option v-for="item in statusOption" :label="item.label" :value="item.value"/>
              </el-select>
              <el-select
                v-model="listQuery.type"
                class="filter-left"
                placeholder="请选择客户类型"
                clearable
                filterable
                size="small"
              >
                <el-option v-for="item in typeOption" :label="item.label" :value="item.value"/>
              </el-select>
            </template>
            <el-button
              size="small"
              class="filter-item filter-left"
              icon="el-icon-search"
              type="primary"
              style="margin-left:5px"
              plain
              @click="search()"
            >
              搜索
            </el-button>
          </div>

          <div ref="filter" class="filter-container">
            <template v-if="isMy || isIntention">
              <el-button
                size="small"
                class="filter-item left"
                type="primary"
                icon="el-icon-plus"
                style="margin-left: 5px;"
                @click="addRow()"
                v-if="isMy || isIntention"
              >
                新建客户
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                type="warning"
                style="margin-left: 5px;"
                icon="el-icon-s-grid"
                @click="setCustomerGroupCollect"
              >
                设置分组
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                type="danger"
                style="margin-left: 5px;"
                icon="el-icon-price-tag"
                @click="setCustomerLabelCollect"
              >
                设置标签
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                type="info"
                style="margin-left: 5px;"
                icon="el-icon-paperclip"
                @click="setCustomerSourceCollect"
                v-if="isMy || isIntention"
              >
                设置来源
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                type="success"
                style="margin-left: 5px;"
                icon="el-icon-success"
                @click="setCustomerDealStatusCollect"
                v-if="isMy || isIntention"
              >
                批量更改成交状态
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                type="warning"
                style="margin-left: 5px;"
                icon="el-icon-star-on"
                @click="setCustomerIntentionCollect"
                v-if="isMy || isIntention"
              >
                批量更新意向状态
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                type="warning"
                style="margin-left: 5px;"
                icon="el-icon-star-on"
                @click="setCustomerEmailCollect"
                v-if="isMy || isIntention"
              >
                新增营销任务
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                style="margin-left: 5px;"
                type="warning"
                icon="el-icon-download"
                @click="openExportCustomer()"
                v-if="(isMy || isIntention) && this.$common.IsInExe()"
              >
                导出
              </el-button>
              <el-button
                size="small"
                class="filter-item left"
                style="margin-left: 5px;"
                icon="el-icon-s-unfold"
                @click="setCustomerIsPrivateCollect(0)"
                v-if="isMy || isIntention"
              >
                批量移入公海
              </el-button>
            </template>
            <template v-else>
              <el-button
                size="small"
                class="filter-item left"
                style="margin-left: 5px;"
                icon="el-icon-s-fold"
                @click="setCustomerIsPrivateCollect(1)"
              >
                批量认领客户
              </el-button>
              <el-button
                type="danger"
                size="small"
                class="filter-item left"
                style="margin-left: 5px;"
                icon="el-icon-delete"
                @click="batchDelete()"
              >
                批量删除客户
              </el-button>
            </template>
          </div>
        </el-col>
      </el-row>
      <el-tab-pane label="联系人" name="contact">
        <el-row>
          <el-table :data="employees" height="calc(100vh - 425px)"  @selection-change="handleSelection">
            <el-table-column type="selection" align="center" />
            <el-table-column align="center" label="序号" width="60" type="index" />
            <el-table-column align="center" label="客户名称" prop="name" show-overflow-tooltip>
              <template slot-scope="{row}">
                <el-link type="primary" @click="infoRow(row.id)">{{row.name}}</el-link>
              </template>
            </el-table-column>
            <el-table-column align="center" label="职位" prop="jobTitle" show-overflow-tooltip>
              <template slot-scope="{row}">
                {{row.jobTitle ? row.jobTitle : '无' }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="手机" prop="mobile">
              <template slot-scope="{row}">
                {{row.mobile ? row.mobile : '无' }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="工作邮箱" prop="email"/>
            <el-table-column align="center" label="个人邮箱" prop="personalEmail"/>
            <el-table-column align="center" label="备注" prop="remarks" show-overflow-tooltip>
              <template slot-scope="{row}">
                {{row.remarks ? row.remarks : '无' }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="归属人" v-if="currentUserInfo.userType == 3">
              <template slot-scope="{row}">
                {{row.user ? row.user.trueName : '无'}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="{row}">
                <el-dropdown style="margin-left: 10px" @command="handleCommand">
                  <el-button size="mini" icon="el-icon-more"/>
                  <el-dropdown-menu slot="dropdown">
                    <template v-if="isMy || isIntention">
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'edit')">编辑客户</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'group')">设置分组</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'source')">设置来源</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'label')">设置标签</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'dealStatus')">更改成交状态</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'intention')">更改意向状态</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'follow')">跟进记录</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'log')">操作日志</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'email',row.name,row.email)">新增营销任务</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'isPrivate',0)">移入公海</el-dropdown-item>
                    </template>
                    <template v-if="isWater">
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'isPrivate',1)">认领客户</el-dropdown-item>
                      <el-dropdown-item :command="beforeHandleCommand(row.id,'delete',1)">删除客户</el-dropdown-item>
                    </template>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="fetchData"
          />
        </el-row>

      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="导出客户"
      :visible.sync="exportCustomerState"
      append-to-body
      width="425px">
      <div class="form-scrollbar" style="height: 150px">
        <div style="line-height: 150px">
          <el-radio-group v-model="exportMode">
            <el-radio :label="1">已勾选的客户导出</el-radio>
            <el-radio :label="2">搜索条件导出</el-radio>
            <el-radio :label="3">全部导出</el-radio>
          </el-radio-group>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportCustomerState = false">取 消</el-button>
        <el-button type="primary" @click="exportCustomer">确 定</el-button>
      </span>
    </el-dialog>
    <drawer :id="customerId" :show.sync="showInfoState" @closeAction="refresh" :action="this.action"/>
    <group :id="collectId" :show.sync="showGroupState" @closeAction="refresh"/>
    <change-deal-status :id="collectId" :show.sync="showDealState" @closeAction="refresh"/>
    <intention :id="collectId" :show.sync="showIntentionState" @closeAction="refresh"/>
    <label :id="collectId" :show.sync="showLabelState" :source="test" @closeAction="refresh"/>
    <source :id="collectId" :show.sync="showSourceState" :source="test" @closeAction="refresh"/>
    <edit :id="customerId" :blockId="id" :show.sync="showState" @closeAction="refresh"/>
    <dialog-follow :id="customerId" :show.sync="showFollowState" @closeAction="refresh"/>
    <dialog-log :id="customerId" :show.sync="showLogState" @closeAction="refresh"/>
    <email-add :emailsTemp="emailData" :show.sync="showBaseFormState" @closeAction="refresh"/>
  </el-drawer>
</template>

<script>
import { UserModule } from '@/store/modules/user'
import { getCustomerList } from '@/api/customer/block'
import Pagination from '@/components/Pagination/index'
import Drawer from './drawer'
import Group from '@/views/customer/common/group'
import Edit from '@/views/customer/index/edit'
import ChangeDealStatus from '@/views/customer/common/changeDealStatus'
import Label from '@/views/customer/common/label'
import Intention from '@/views/customer/common/intention'
import Source from '@/views/customer/common/source'
import DialogFollow from '@/views/customer/index/dialogFollow'
import DialogLog from '@/views/customer/index/dialogLog'
import EmailAdd from '@/views/customer/index/emailAdd'
import { deleteCustomer, getCustomerAllIds, getCustomerIds, SetIsPrivate } from '@/api/customer'

export default {
  name: 'BlockDrawer',
  components: { Pagination, Group, Edit, Drawer, ChangeDealStatus, Label, Intention, Source, DialogFollow, DialogLog, EmailAdd },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: {
      type: [Number, String],
      default: ''
    },
    source: {
      type: [Number, String],
      default: ''
    },
    action: {
      type: [Number, String],
      default: ''
    },
    closeAction: {
      type: String,
      default: ''
    }
  },
  created() {
    this.checkTab()
  },
  data() {
    return {
      test: 'customer',
      currentUserInfo: UserModule,
      exportMode: 1,
      exportCustomerState: false,
      isMy: false,
      isIntention: false,
      isWater: false,
      emailData: [],
      showInfoState: false,
      showBaseFormState: false,
      showGroupState: false,
      showDealState: false,
      showLabelState: false,
      showIntentionState: false,
      showSourceState: false,
      showFollowState: false,
      showLogState: false,
      showState: false,
      drawerLoading: true,
      dialogVisible: this.show,
      direction: 'rtl',
      activeName: 'contact',
      info: {
        title: 'Test_Title'
      },
      employees: [],
      selection: [],
      collectId: '',
      listQuery: {
        status: '',
        type: '',
        limit: 20,
        page: 20,
        mobile: ''
      },
      statusOption: [
        { label: '未成交', value: 0 },
        { label: '已成交', value: 1 },
        { label: '已跟进', value: 2 },
        { label: '未跟进', value: 3 }
      ],
      typeOption: [
        { label: '全球搜索', value: 1 },
        { label: '数据营销', value: 2 },
        { label: '外部导入', value: 3 }
      ],
      total: 0,
      customerId: 0
    }
  },
  inject: ['showProgressDialog'],
  methods: {
    checkTab() {
      // 初始化
      this.isMy = false
      this.isIntention = false
      this.isWater = false

      if (this.action == 1) {
        this.isMy = true
      }// 我的客户
      if (this.action == 2) {
        this.isIntention = true
      }// 意向客户
      if (this.action == 3) {
        this.isWater = true
      }//
    },
    open() {
      this.listQuery = {
        status: '',
        type: '',
        limit: 20,
        page: 1,
        mobile: ''
      },
      this.customerId = 0
      this.showBaseFormState = false
      this.showLogState = false
      this.showFollowState = false
      this.showIntentionState = false
      this.showGroupState = false
      this.showLabelState = false
      this.showSourceState = false
      this.showDealState = false
      this.showState = false
      this.showInfoState = false
      this.exportCustomerState = false
      this.drawerLoading = true
      this.fetchData()
    },
    async fetchData() {
      const params = {
        action: this.action,
        blockId: this.id,
        form: this.source,
        status: this.listQuery.status.length ? this.listQuery.status : -1,
        type: this.listQuery.type,
        limit: this.listQuery.limit,
        page: this.listQuery.page,
        mobile: this.listQuery.mobile
      }
      await getCustomerList(params).then((res) => {
        this.employees = res.data.employees.items
        this.total = res.data.employees.total
        this.info = res.data.info
        setTimeout(() => {
          this.drawerLoading = false
        }, 0.5 * 1000)
      }).catch(() => {
        setTimeout(() => {
          this.drawerLoading = false
        }, 0.5 * 1000)
      })
    },
    infoRow(id) {
      console.log(id)
      this.customerId = id
      this.showInfoState = true
    },
    handleClose(done) {
      this.$emit('update:show', false)
    },
    refresh() {
      this.open()
    },
    search() {
      this.open()
    },
    handleSelection(val) {
      this.selection = val
    },
    setCustomerGroupCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置分组的客户'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showGroupState = true
    },
    setCustomerLabelCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置标签的客户'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showLabelState = true
    },
    setCustomerSourceCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置来源的客户'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showSourceState = true
      console.log(this.showSourceState, this.collectId)
    },
    setCustomerDealStatusCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量更改成交状态'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showDealState = true
    },
    setCustomerIntentionCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量更新意向状态'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showIntentionState = true
    },
    batchDelete() {
      if (this.selection.length <= 0) {
        this.$message('请选择需要批量删除的客户')
        return false
      }
      const uploadItems = [
        { name: '客户', num: this.selection.length, action: this.batchDeleteFunc, data: this.selection }
      ]
      const uploadColumns = [
        { label: '客户', key: 'name', popover: true }
      ]
      this.showProgressDialog(uploadItems, uploadColumns, this.refresh, { title: '批量客户删除，此操作不可逆' })
    },
    async batchDeleteFunc({ item, message }) {
      await deleteCustomer(item.id).then((res) => {
        message.success('[' + item.name + '] 删除成功')
      }).catch((res) => {
        message.failed('[' + item.name + '] ' + res.message)
      })
    },
    setCustomerIsPrivateCollect(val = 0) {
      if (this.selection.length <= 0) {
        let msg = ''
        if (val == 0) {
          msg = '请勾选需要批量移入公海的客户'
        } else {
          msg = '请勾选需要批量认领的客户'
        }
        this.$message({
          type: 'info',
          message: msg
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.setCustomerIsPrivateRes(val)
    },
    addRow() {
      this.customerId = ''
      this.showState = true
    },
    setCustomerIsPrivateRes(val = 0) {
      let msg = ''
      let title = ''
      if (val == 0) {
        title = '移入'
        msg = '确认要将该客户移入公海？'
        if (typeof this.id !== 'object') {
          msg = '确认要将客户移入公海？'
        }
      } else {
        title = '认领'
        msg = '确认要认领该客户？'
        if (typeof this.id !== 'object') {
          msg = '确认要认领客户？'
        }
      }

      this.$confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const data = { ids: this.collectId, value: val, BlockId: this.info.id }

        if (typeof data.ids !== 'object') {
          data.ids = [data.ids]
        }
        await SetIsPrivate(data).then((res) => {
          this.$notify({
            title: '成功',
            message: `${title}成功`,
            type: 'success',
            duration: 2000
          })
          // this.fetchData();
          // todo 更新
          this.$emit('closeAction')
        })
      }).catch(() => {

      })
    },
    setCustomerEmailCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量新增营销任务'
        })
        return false
      }
      this.emailData = []
      const data = {}
      for (const i in this.selection) {
        this.emailData.push({
          id: this.selection[i].id,
          name: this.selection[i].name,
          email: this.selection[i].email
        })
      }
      this.showBaseFormState = true
    },
    openExportCustomer() {
      this.exportMode = 1
      this.exportCustomerState = true
    },
    async exportCustomer() {
      const mode = this.exportMode
      switch (mode) {
        case 1:
          if (this.selection.length <= 0) {
            this.$message({
              type: 'info',
              message: '请勾选需要导出的客户'
            })
            return false
          }
          const ids = []
          for (const i in this.selection) {
            ids.push(this.selection[i].id)
          }
          const _this = this
          this.$common.ExeInvoke(function(f) {
            f.ExportClient(ids)
            _this.exportCustomerState = false
          })
          break
        case 2:
          const listQuery = JSON.parse(JSON.stringify(this.listQuery))
          if (listQuery.status === '') {
            listQuery.status = -1
          }
          await getCustomerIds(listQuery).then((res) => {
            console.log(res)
            if (!res.data.length) {
              this.$message({
                type: 'warning',
                message: '未获取到客户数据'
              })
            }
            const ids = res.data
            this.$common.ExeInvoke(function(f) {
              f.ExportClient(ids)
              _this.exportCustomerState = false
            })
          })
          break
        case 3:
          const params = {}
          params.action = this.listQuery.action
          await getCustomerAllIds(params).then((res) => {
            if (!res.data.length) {
              this.$message({
                type: 'warning',
                message: '未获取到客户数据'
              })
            }
            const ids = res.data
            this.$common.ExeInvoke(function(f) {
              f.ExportClient(ids)
              _this.exportCustomerState = false
            })
          })
          break
      }
    },
    beforeHandleCommand(scope, command, val1 = 0, val2 = null) {
      return {
        scope: scope,
        command: command,
        val: val1,
        val2: val2
      }
    },
    handleCommand(command) {
      switch (command.command) {
        case 'edit':
          this.customerId = command.scope
          this.showState = true
          break
        case 'group':
          this.collectId = command.scope
          this.showGroupState = true
          break
        case 'source':
          console.log('source')
          this.collectId = command.scope
          this.showSourceState = true
          break
        case 'label':
          console.log('label')
          this.collectId = command.scope
          this.showLabelState = true
          break
        case 'dealStatus':
          this.collectId = command.scope
          this.showDealState = true
          break
        case 'intention':
          this.collectId = command.scope
          this.showIntentionState = true
          break
        case 'follow':
          this.collectId = command.scope
          this.showFollowState = true
          break
        case 'log':
          this.collectId = command.scope
          this.showLogState = true
          break
        case 'isPrivate':
          this.collectId = command.scope
          this.setCustomerIsPrivateRes(command.val)
          break
        case 'delete':
          this.collectId = command.scope
          this.customerDelete()
          break
        case 'email':
          this.emailData = []
          const data = {
            id: command.scope,
            name: command.val,
            email: command.val2
          }
          this.emailData.push(data)
          this.showBaseFormState = true
          break
      }
    },
    customerDelete() {
      this.$confirm('确认要删除客户,此操作不可逆', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteCustomer(this.collectId).then((res) => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          console.log(1111)
          this.$emit('closeAction')
        })
      }).catch(() => {

      })
    }
  },
  watch: {
    show() {
      this.dialogVisible = this.show
      if (this.show) {
        this.open()
      }
    }
  }
}
</script>

<style scoped>
.el-input::v-deep .el-input-group__prepend {
  padding: 0;
  width: 200px;
  border:unset;
}

.el-cascader::v-deep .e-input{
  margin-top:-1px;
}

/* .el-input::v-deep .el-input-group__prepend >div.el-cascader.el-cascader--medium.el-cascader >div.el-input.el-input--medium.el-input--suffix > .el-input__inner{ */
/* border-right: unset; */
/* } */
.head-item {
  padding: 5px 0 5px 0;
}

</style>
